
import { checkPromotionCode, createPromotionCode, getPromotionCode } from '@/services/promotion/youhuimajiekou';
import { PageContainer } from '@ant-design/pro-layout';
import { useModel, useRequest } from '@umijs/max';
import { Button, Card, Col, Flex, Form, Input, Row, Space, Table, message } from "antd";
import { useEffect, useRef, useState } from 'react';
import ModalAsync from '@/components/ModalAsync';
import { flushSync } from 'react-dom';
import { orderReCharge, returnOrderInfo } from '@/services/order/dingdanjiekou'

interface ModalSettings {
  type: string;
  title: string;
}

const AccountCenter = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const getPromotionCodeParams = {}
  const [len, setlen] = useState<any>(0)
  const [dataSource, setDataSource] = useState<any>([])
  const [realLen, setRealLen] = useState<any>(0)
  const [openModal, setOpenModal] = useState<any>(false)
  const [openModal1, setOpenModal1] = useState<any>(false)
  const [modalSettings, setModalSettings] = useState<ModalSettings>({ type: '', title: '' });
  const [form] = Form.useForm();
  const [form1] = Form.useForm();
  const formRef1 = useRef<any>();
  const formRef2 = useRef<any>();
  const [loadings, setLoadings] = useState<boolean>(false);


  useEffect(() => {
    getPromotionCodeList(getPromotionCodeParams)
  }, [])

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleOpenModal = (type: any) => {
    let title = '';
    switch (type) {
      case "recharge":
        form.resetFields()
        title = "充值"
        break;
      case "acquire":
        title = "订单确认"
        break;
      default:
        break;
    }
    setOpenModal(true)
    setModalSettings({ type, title })
  }

  const getPromotionCodeList = async (params: any) => {
    const res = await getPromotionCode(params)
    if (res.code === 0) {
      setDataSource(res.data)
      setlen(res.data?.length)
      setRealLen(initialState?.currentUser?.countPromotion)
    } else {
      message.error(res.message)
    }
  }

  const ok = async () => {
    switch (modalSettings?.type) {
      case 'recharge':
        return formRef1.current?.submit();
      case 'acquire':
        return formRef2.current?.submit();
      default:
        return true;
    }
  };

  const validatePromotionCode = async (values: any) => {
    const { codes } = values
    // 如果优惠码为空，则不进行校验
    if (!codes) {
      form.setFields([{ name: 'codes', errors: [] }]);
      return true;
    }
    const res = await checkPromotionCode({ codes: codes });
    if (res.code !== 0) {
      form.setFields([{ name: 'codes', errors: ['优惠码无效'] }]);
      return false;
    }
    return true;
  }

  const validateAmount = (values: any) => {
    const { amount } = values
    if (amount < 1) {
      form.setFields([{ name: 'amount', errors: ['金额必须大于0'] }]);
      return false;
    }
    return true;
  }

  // const generateContent = () => {
  //   if (modalSettings?.type === 'recharge') {
  //     return (
  //       <>
  //         <Form
  //           form={form}
  //           layout="vertical"
  //           onFinish={async (values: any) => {

  //             const res = await payOrder(values)
  //             if (res.code == 0) {
  //               setOpenModal(false)
  //               handleOpenModal('acquire')
  //               setOpenModal1(true)
  //               form1.setFieldsValue(res.data)
  //             } else {
  //               message.error(res.message)
  //               setOpenModal(false)
  //             }

  //           }}
  //         >
  //           <Form.Item
  //             name="amount"
  //             label="金额"
  //             rules={[
  //               {
  //                 required: true,
  //                 message: '请输入优惠码',
  //               },
  //             ]}
  //           >
  //             <Input />
  //           </Form.Item>
  //           <Form.Item
  //             name="code"
  //             label="优惠码"
  //           >
  //             <Input />
  //           </Form.Item>
  //         </Form>
  //       </>
  //     )
  //   } else {
  //     return (
  //       <>
  //         <Form
  //           form={form1}
  //           onFinish={async (values) => {
  //           }}
  //         >
  //           <Form.Item
  //             name="subject"
  //             label="商品名称"
  //           >
  //             <Input disabled />
  //           </Form.Item>
  //           <Form.Item
  //             name="amount"
  //             label="总金额"
  //           >
  //             <Input disabled />
  //           </Form.Item>
  //           <Form.Item
  //             name="discountRate"
  //             label="优惠率"
  //           >
  //             <Input disabled />
  //           </Form.Item>
  //           <Form.Item
  //             name="realAmount"
  //             label="优惠后总金额"
  //           >
  //             <Input disabled />
  //           </Form.Item>
  //         </Form>
  //       </>
  //     )
  //   }

  // }

  const generateContent1 = (setLoadings: any) => {
    return (
      <>
        <Form

          ref={formRef1}
          form={form}
          layout="horizontal"
          onFinish={async (values: any) => {
            const x = validateAmount(form.getFieldsValue())
            if (!x) {
              setLoadings(false)
              return;
            }
            const y = await validatePromotionCode(form.getFieldsValue())
            if (!y) {
              setLoadings(false)
              return;
            }
            const res = await returnOrderInfo(values)
            if (res.code === 0) {
              handleOpenModal('acquire')
              form1.setFieldsValue({
                codes: res?.data?.codes || '',
                subject: res?.data?.subject || '', // 假设 res.data.subject 是字符串类型
                amount: res?.data?.amount || 0, // 假设 res.data.amount 是字符串类型
                discountRate: res?.data?.discountRate || 0.0, // 假设 res.data.discountRate 是字符串类型
                realAmount: res?.data?.realAmount || 0, // 假设 res.data.realAmount 是字符串类型
              });
              setOpenModal(false)
              setOpenModal1(true)
              form.resetFields()
            } else {
              message.error(res.message)
              setOpenModal(false)
              form.resetFields()
            }
            setLoadings(false)
          }}
          onFinishFailed={() => setLoadings(false)}
        >
          <Form.Item
            name="amount"
            label="金额"
            rules={[
              {
                required: true,
                message: '请输入金额',
              },
              {
                pattern: /^\d+$/,
                message: '金额必须是大于0的整数',
              },
            ]}
          >
            <Input onBlur={(e) => { validateAmount(form.getFieldsValue()) }} />
          </Form.Item>
          <Form.Item
            name="codes"
            label="优惠码"
          >
            <Input onBlur={(e) => { validatePromotionCode(form.getFieldsValue()) }} />
          </Form.Item>
        </Form>
      </>
    )
  }

  const generateContent2 = () => {
    return (
      <>
        <Form
          ref={formRef2}
          form={form1}
          layout='horizontal'
          // style={{ maxWidth: 600 }}
          labelCol={{ span: 5 }}  // 调整 label 的宽度
          wrapperCol={{ span: 16 }}  // 调整输入框的宽度
          onFinish={async (values) => {
            console.log(123)
            const res = await orderReCharge(values)
            if (res.code === 0) {
              // window.open(res.data)
              window.location.href = res.data ?? '';
              getPromotionCodeList(getPromotionCodeParams)
              fetchUserInfo()
            } else {
              message.error(res.message)
            }
            setOpenModal1(false)
            setLoadings(false);
          }}
          onFinishFailed={() => setLoadings(false)}
        >
          <Form.Item
            name="codes"
            label="优惠码"
          >
            <Input disabled defaultValue={"无"} value={"无"} />
          </Form.Item>
          <Form.Item
            name="subject"
            label="商品名称"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="amount"
            label="总金额"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="discountRate"
            label="优惠率"
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            name="realAmount"
            label="优惠后总金额"
          >
            <Input disabled />
          </Form.Item>
        </Form>
      </>
    )


  }

  const genPromotionCode = async () => {
    const res = await createPromotionCode()
    if (res.code == 0) {
      message.success("优惠码生成成功")
      getPromotionCodeList(getPromotionCodeParams)
    } else {
      message.error(res.message)
    }

  }

  const columns = [
    {
      title: '优惠码',
      dataIndex: 'code',
      key: 'code',
    },
  ]

  return (
    <PageContainer ghost>
      <Row gutter={24}>
        <Col span={12}>
          <Card title="账户信息">
            <Flex wrap="wrap" gap="small" vertical>
              <p>
                用户名: {initialState?.currentUser?.username}
              </p>
              <p>
                豆币: {initialState?.currentUser?.amount}
              </p>
              <p>
                <Button type='primary' onClick={() => handleOpenModal('recharge')}>充值</Button>
              </p>
            </Flex>
          </Card>
        </Col>

        <Col span={12}>
          <Card title="优惠码">
            {len < realLen && <Button type='primary' onClick={genPromotionCode}>
              生成优惠码
            </Button>}
            {len > 0 && <Table
              rowKey={(record) => record.id}
              dataSource={dataSource}
              columns={columns}
              pagination={false}
              bordered

            />}

          </Card>
        </Col>
      </Row >

      <ModalAsync
        open={openModal}
        setVisible={setOpenModal}
        title={modalSettings?.title}
        ok={ok}
        generateContent={generateContent1}
      />

      <ModalAsync
        open={openModal1}
        setVisible={setOpenModal1}
        title={modalSettings?.title}
        ok={ok}
        generateContent={generateContent2}
      />
    </PageContainer >

  );
};

export default AccountCenter;